package com.netty.netty.high.demo4;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LoggingHandler;

public class NettyClient {


    //把消息加工成可以被行解码器识别的消息
    private static String getMsg(String oldMsg){

        oldMsg+='\r';
        return oldMsg;
    }

  public static void main(String[] args) {

      NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
      try{
      new Bootstrap()
              .group(nioEventLoopGroup)
              .channel(NioSocketChannel.class)
              .handler(new ChannelInitializer<Channel>() {
                  @Override
                  protected void initChannel(Channel ch) throws Exception {

                      ch.pipeline().addLast(new LoggingHandler());

                      ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){

                          @Override
                          public void channelActive(ChannelHandlerContext ctx) throws Exception {

                              ByteBuf buffer = ctx.alloc().buffer(16);

                              for(int i=0;i<10;i++){
                                  buffer.retain();
                                  String msg = getMsg("hello world");
                                  buffer.writeBytes(msg.getBytes("utf-8"));
                                  ctx.channel().writeAndFlush(buffer);
                                  //清理缓存,防止数据堆叠
                                  buffer.clear();
                              }

                              ch.close();//关闭Channel
                              ChannelFuture closeFuture = ch.closeFuture();
                              closeFuture.addListener(new ChannelFutureListener() {
                                  @Override
                                  public void operationComplete(ChannelFuture future) throws Exception {
                                      nioEventLoopGroup.shutdownGracefully();
                                  }
                              });
                          }
                      });
                  }
              }).connect("localhost",8080);
      }catch (Exception e){
          e.printStackTrace();
      }

  }
}
